package net.gazhi.delonix.rbac.service;

import java.util.LinkedHashSet;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import net.gazhi.delonix.core.jpa.AbstractEntityService;
import net.gazhi.delonix.rbac.entity.LoginUser;
import net.gazhi.delonix.rbac.entity.MenuItem;

@Service
public class MenuItemService extends AbstractEntityService<MenuItem> {

	/**
	 * 根据用户ID查找权限菜单(只返回跟节点)<br>
	 * 如果是超级管理员，返回所有根菜单节点
	 * 
	 * @param userId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public LinkedHashSet<MenuItem> findRootMenuItems(int userId) {
		Criteria query = dao.createCriteria(MenuItem.class, "it").addOrder(Order.asc("it.id"));
		// 如果是超级管理员就不需要限定角色关联，直接返回所有菜单项
		if (userId != LoginUser.SUPER_ADMIN_ID) {
			query.createAlias("it.action", "act").createAlias("act.roles", "r").createAlias("r.users", "u");
			query.add(Restrictions.eq("u.id", userId)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		}
		List<MenuItem> items = query.list();
		LinkedHashSet<MenuItem> roots = new LinkedHashSet<MenuItem>();
		for (MenuItem it : items) {
			MenuItem root = this.navToRootMenuItem(it);
			roots.add(root);
		}
		return roots;
	}

	/**
	 * 递归到父节点，并设置 grantChilds
	 * 
	 * @param menu
	 * @return
	 */
	private MenuItem navToRootMenuItem(MenuItem item) {
		if (item.getParent() == null) {
			return item;
		}
		item.getParent().getChildItems().add(item);
		return this.navToRootMenuItem(item.getParent());
	}

}
